package work.sby.service;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import work.sby.mapper.BrandMapper;
import work.sby.pojo.Brand;

import java.util.List;
import work.sby.util.SqlSessionFactoryUtils;

public class BrandService {
    //调用BrandMapper的selectAll方法，返回所有品牌信息
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();



//查询所有
    public List<Brand> selectAll(){

//2.创建SqlSession对象
        SqlSession sqlSession = factory.openSession();
        
//获取brandmapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//        3.调用方法
        List<Brand> brands = mapper.selectAll();
//        4.关闭SqlSession
        sqlSession.close();
        return brands;
    }


    public void add(Brand brand){

        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4. 调用方法
        mapper.add(brand);

        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();

    }
    public Brand selectById(int id){
        //调用BrandMapper.selectAll()

        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4. 调用方法
        Brand brand = mapper.selectById(id);

        sqlSession.close();

        return brand;
    }
    public List<Brand> selectByBrandName(String brandName){
        //调用BrandMapper.selectAll()

        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4. 调用方法
        List<Brand> brand = mapper.selectByBrandName(brandName);

        sqlSession.close();

        return brand;
    }
    public void update(Brand brand){

        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4. 调用方法
        mapper.update(brand);

        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();

    }
    public void deleteById(int id){
        //调用BrandMapper.selectAll()

        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4. 调用方法
        mapper.deleteById(id);
        sqlSession.commit();
        sqlSession.close();


    }
}
